import { useState, useCallback } from 'react';
import { message } from 'antd';

/**
 * 通用表单弹窗Hook
 * 简化表单弹窗的状态管理
 */
export function useFormModal<T = Record<string, unknown>>() {
  const [visible, setVisible] = useState(false);
  const [isAddMode, setIsAddMode] = useState(true);
  const [currentRecord, setCurrentRecord] = useState<T | null>(null);
  const [loading, setLoading] = useState(false);

  // 打开添加弹窗
  const openAddModal = useCallback(() => {
    setIsAddMode(true);
    setCurrentRecord(null);
    setVisible(true);
  }, []);

  // 打开编辑弹窗
  const openEditModal = useCallback((record: T) => {
    setIsAddMode(false);
    setCurrentRecord(record);
    setVisible(true);
  }, []);

  // 关闭弹窗
  const closeModal = useCallback(() => {
    setVisible(false);
    setCurrentRecord(null);
    setLoading(false);
  }, []);

  // 处理提交（带loading状态）
  const handleSubmit = useCallback(async (
    submitFn: (values: T, isAddMode: boolean, currentRecord?: T | null) => Promise<void> | void
  ) => {
    setLoading(true);
    try {
      await submitFn;
      closeModal();
    } catch (error) {
      console.error('提交失败:', error);
      message.error('操作失败，请重试');
    } finally {
      setLoading(false);
    }
  }, [closeModal]);

  return {
    visible,
    isAddMode,
    currentRecord,
    loading,
    openAddModal,
    openEditModal,
    closeModal,
    handleSubmit,
  };
}
